<template>
    <div class="u3-upload">
        <input
            type="file"
            ref="inputFile"
            style="display: none;"
            id="file"
            accept="image/jpeg"
            @change="fileChange($event)"
        />
        <template v-if="type === 'image'">
            <div
                v-if="imageSrc === ''"
                class="u3-upload-select"
                @mouseover="mouseover()"
                @mouseout="mouseout()"
                @click="$refs.inputFile.click()"
            >
                <i :class="iconClass" class="u3-upload-select__icon"></i>
                <p class="u3-upload-select__text">上传图片</p>
                <p class="u3-upload-select__tips">只支持.jpg格式</p>
            </div>
            <div
                v-else
                class="u3-upload-image"
                @click="$refs.inputFile.click()"
            >
                <img :src="imageSrc" alt="">
            </div>
        </template>
    </div>
</template>
<script>
import { getAliyunToken, getPlatForm } from 'javascript/api/setupApi';
import configAxios from 'javascript/api/configAxios';
import aliPolicyServer from 'javascript/fileuploader/ali/aliPolicyServer';

export default {
    props: {
        type: {
            type: String,
            default: 'image',
        },
        src: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            // icon
            iconClass: 'u3-upload-add',

            // 文件
            fileArr: [],

            // 本地图片地址
            imageSrc: this.src,

            // 上传阿里云
            uploaderObj: '',
            msg: '',
            file: null,
            fileRecord: [],

            // 上传阿里云
            stObj: {},
        }
    },
    mounted() {
        this.init();
        console.log(getPlatForm());
    },
    methods: {
        init() {
            /* eslint-disable */
            this.uploaderObj = new up366AliUploader({
                platForm: getPlatForm()
            });
            this.uploaderObj.init();

            const _this = this;
            this.uploaderObj.uploader.on('fileQueued', function(file) {
                console.log(file);
                _this.file = file;
                _this.msg = '准备上传';
            })
            this.uploaderObj.uploader.on('uploadProgress', function() {
                _this.msg = '正在上传';
            })
            this.uploaderObj.uploader.on('uploadSuccess', function() {
                _this.msg = '上传成功';
                _this.complete();
            })
            this.uploaderObj.uploader.on('uploadError', function() {
                _this.msg = '上传失败';
                _this.$notify({
                    title: '上传失败',
                    message: '网络原因，请重试！',
                    type: 'error',
                })
            })
        },
        /**
         * 选择图片文件hover
         */
        mouseover() {
            this.iconClass = 'u3-upload-add__hover';
        },
        mouseout() {
            this.iconClass = 'u3-upload-add';
        },
        /**
         * 选择文件
         */
        fileChange(event) {
            const Event = event;
            const fileList = Event.target.files;
            this.fileArr = [];

            for (let i = 0; i < fileList.length; i++) {
                if (this.type === 'image') {
                    if (fileList[i].type !== 'image/jpeg') {
                        this.$notify({
                            title: '不正确的文件类型',
                            type: 'error',
                        });
                        break;
                    }
                }

                if (fileList.length - 1 === i) {
                    for (let j = 0; j < fileList.length; j++) {
                        this.fileArr.push(fileList[j]);
                    }
                }
            }
            Event.target.value = '';

            // 上传阿里云
            this.upload();
        },
        upload() {
            if (this.fileArr.length === 0) return;
            console.log(this.fileArr)

            for (let i = 0 ;i < this.fileRecord.length; i++) {
                if (this.fileArr[0].name === this.fileRecord[i].name) {
                    this.imageSrc = this.fileRecord[i].imageSrc;
                    this.$emit('getFile', this.imageSrc);
                }
            }

            this.uploaderObj.uploader.addFiles(this.fileArr[0]);
            this.uploaderObj.uploader.upload();
        },
        complete() {
            const info = this.file.fileObjectInfo;
            this.imageSrc = info.previewUrl;
            this.fileRecord.push({name: this.file.name, imageSrc: info.previewUrl});
            this.$emit('getFile', info.previewUrl);
        },
        /**
         * 显示文件
         */
        showFile() {
            if (this.fileArr.length === 0) return;
            const vue = this;

            if (this.type === 'image') {
                // 实例化FileReader API
                const freader = new FileReader();
                freader.readAsDataURL(this.fileArr[0]);
                freader.onload = function(e) {
                    vue.imageSrc = e.target.result;
                }
            }
        },
        emitFile() {
            if (this.fileArr.length === 0) return;

            this.$emit('getFile', this.fileArr[0]);
        },
        uploadAli() {
            if (this.fileArr.length === 0) return;

            getAliyunToken().then((res) => {
                console.log(res);
                if (res.result.code === 0) {
                    const httpPost = configAxios.post;
                    const url = window.location.protocol + '//' + res.data.bucketname + '.' + res.data.defaulthostid;
                    let stObj = {
                        aliServer: window.location.protocol + '//' + res.data.bucketname + '.' + res.data.defaulthostid,
                        securityToken: res.data.securityToken,
                        AccessKeyId: res.data.tmpAkId,
                        AccessSecret: res.data.tmpAkSecret
                    }

                    const file = {};
                    var d = new Date();
                    var month = d.getMonth() + 1;
                    month = month > 9 ? month : ('0' + month);

                    var policyObj = {}
                    policyObj.OSSAccessKeyId = stObj.AccessKeyId;
                    policyObj.securityToken = stObj.securityToken;

                    var policy = aliPolicyServer.getPolicySignature({
                        expiration: new Date(d.getTime() + 3600000).toISOString(),
                        conditions: [
                        {bucket: stObj.bucketName},
                        ["starts-with", "$key", d.getFullYear() + '/' + month + '/' + d.getDate() + '/'],
                        ["eq", "$x-oss-security-token", stObj.securityToken]
                        ]
                    }, stObj.AccessSecret);

                    policyObj.policy = policy.policyBase64Str;
                    policyObj.Signature = policy.signature;

                    file.policyObj = policyObj;

                    const formData = new FormData();
                    formData.append('file', this.fileArr[0]);
                    formData.append('key', d.getFullYear() + '/' + month + '/' + d.getDate());
                    formData.append('OSSAccessKeyId', file.policyObj.OSSAccessKeyId);
                    formData.append('x-oss-security-token', file.policyObj.securityToken);
                    formData.append('policy', file.policyObj.policy);
                    formData.append('Signature', file.policyObj.Signature);


                    const config = {
                        headers: {
                            'Content-Type': 'multipart/form-data;',
                        },
                        transformRequest: [function(data) {return data;},]
                    }

                    httpPost(url, formData, config).then((res) => {
                        console.log(res);
                    })
                } else {
                    // 获取阿里云st失败
                }
            })
        },
    },
}
</script>
<style lang="scss" scoped>
    .u3-upload {
        &-select {
            width: 124px;
            height: 124px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            align-items: center;
            border: 1px solid #E8E8E8;
            border-radius: 2px;
            line-height: 14px !important;
            &:hover {
                border: 1px solid #6C92FF;
                cursor: pointer;
            }
            &__icon {
                margin: 28px 0 12px;
            }
            &__text {
                font-size: 14px;
                color: #333333;
            }
            &__tips {
                font-size: 12px;
                color: #999999;
                margin: 5px 0 20px;
            }
        }
        &-image {
            width: 124px;
            height: 124px;
            box-sizing: border-box;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            cursor: pointer;
            border: 1px solid #E8E8E8;
            border-radius: 2px;
            & img {
                position: relative;
                display: block;
                max-width: 124px;
            }
        }
    }
</style>